package com.example.usbhidtool.utils

import android.content.Context
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
import kotlin.experimental.and

/**
 * 获取文件MD5
 */
object MD5Util {
    /**
     * 获取assets目录下文件的MD5
     */
    fun getAssertFileMD5(context: Context, fileName: String): String? {
        //获取文件大小
        val manager = context.assets
        val intpuStream = manager.open(fileName)
        val bins = BufferedInputStream(intpuStream)
        val buffer = ByteArray(1024)
        val digest: MessageDigest
        var len: Int
        try {
            digest = MessageDigest.getInstance("MD5")
            while (bins.read(buffer, 0, 1024).also { len = it } != -1) {
                digest.update(buffer, 0, len)
            }
            bins.close()
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
        return bytesToHexString(digest.digest())
    }

    /**
     * 获取Sdcard下文件的MD5
     */
    fun getSdCardFileMd5(fileName: String): String? {
        //获取文件大小
        try {
            val file = File(fileName)
            val bins = BufferedInputStream(FileInputStream(file))
            val buffer = ByteArray(1024)
            val digest: MessageDigest
            var len: Int
            try {
                digest = MessageDigest.getInstance("MD5")
                while (bins.read(buffer, 0, 1024).also { len = it } != -1) {
                    digest.update(buffer, 0, len)
                }
                bins.close()
            } catch (e: Exception) {
                e.printStackTrace()
                return null
            }
            return bytesToHexString(digest.digest())
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun bytesToHexString(src: ByteArray?): String? {
        val stringBuilder = StringBuilder("")
        if (src == null || src.isEmpty()) {
            return null
        }
        for (i in src.indices) {
            val v: Int = src[i].toInt() and 0xFF
            val hv = Integer.toHexString(v)
            if (hv.length < 2) {
                stringBuilder.append(0)
            }
            stringBuilder.append(hv)
        }
        return stringBuilder.toString()
    }
}